package com.wyy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wyy.error.BusinessException;
import com.wyy.error.EnumBusinessError;
import com.wyy.mapper.OrderMapper;
import com.wyy.mapper.UserMapper;
import com.wyy.pojo.AppreciatesOrder;
import com.wyy.pojo.OrderModel;
import com.wyy.pojo.UserPojo;
import com.wyy.pojo.Users;
import com.wyy.service.OrderService;
import com.wyy.util.MyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program: gytcb
 * @author: 吴磊
 * @create: 2021-06-30 19:20
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 删除超时并未支付的订单
     */
    @Override
    public void deleteTimeOutOrder() {
        List<AppreciatesOrder> AppreciatesOrders = orderMapper.selectList(null);
        AppreciatesOrders.forEach(order -> {
            String orderId = order.getOrderId();
            String orderDate = order.getOrderDate();
            boolean flag = false;
            long nowLongDate = System.currentTimeMillis();
            long orderLongTime = MyUtil.parseTimeToString(orderDate);
            if (order.getOrderStatus() == 0 && (nowLongDate - orderLongTime) > (1000 * 60 * 30)) {
                flag = true;
            }
            if (flag) {
                QueryWrapper<AppreciatesOrder> wrapper = new QueryWrapper<>();
                wrapper.eq("order_id", orderId);
                orderMapper.delete(wrapper);
            }
        });
    }

    /**
     * 获取所有的订单
     *
     * @return
     */
    @Override
    public Map<String, Object> getAllOrder(UserPojo userPojo) {
        Integer curPage = Integer.parseInt(userPojo.getCurPage());
        HashMap<String, Object> map = new HashMap<>();
        //分页，根据前端传过来的 p 页数
        Page<AppreciatesOrder> page = new Page<>(curPage, 10);
        Page<AppreciatesOrder> orderPage = orderMapper.selectPage(page, null);
        //总篇数
        long total;
        //总页数
        long pages;
        total = orderPage.getTotal();
        pages = orderPage.getPages();
        List<AppreciatesOrder> orderList = orderPage.getRecords();

        List<OrderModel> orderModelList = orderList.stream().map(o -> {
            OrderModel orderModel = new OrderModel();
            BeanUtils.copyProperties(o, orderModel);
            return orderModel;
        }).collect(Collectors.toList());

        orderModelList = orderModelList.stream().map(o -> {
            String userId = o.getOrderBuyerId();
            QueryWrapper<Users> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            Users users = userMapper.selectOne(wrapper);
            if (users == null) {
                o.setUserNickname("匿名");
                o.setUserProfilePhoto("http://121.196.111.148:8081/blog/image/5b61e1f0-7557-4b59-96a1-5e3fb75fb65a.png");
            } else {
                BeanUtils.copyProperties(users, o);
            }
            return o;
        }).collect(Collectors.toList());
        map.put("total", total);
        map.put("orders", orderModelList);
        map.put("totalPage", pages);
        return map;
    }

    /**
     * 根据ID删除订单
     *
     * @param appreciatesOrder
     * @return
     */
    @Override
    public void deleteOrderById(AppreciatesOrder appreciatesOrder) {
        String orderId = appreciatesOrder.getOrderId();
        QueryWrapper<AppreciatesOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        if (StringUtils.isEmpty(orderId)) {
            throw new BusinessException(EnumBusinessError.PARAMETER_INVALID_ERROR);
        }
        int i = orderMapper.delete(wrapper);
        if (i <= 0) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "删除订单失败");
        }
    }
}
